package com.jike.noobmoney.mvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jike.noobmoney.R;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.LoginUserEntity;
import com.jike.noobmoney.net.RetrofitHelper;
import com.jike.noobmoney.util.PerfectClickListener;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Create by xuke on 2017/10/28
 * 验证码登录
 */
public class LoginActivity extends BaseActivity {

    @BindView(R.id.img_logo)
    ImageView imgLogo;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.rl_clearPhone)
    RelativeLayout rlClearPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.rl_clearPassword)
    RelativeLayout rlClearPassword;
    @BindView(R.id.ll_login)
    LinearLayout llLogin;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_regist)
    TextView tvRegist;
    @BindView(R.id.tv_forgot_password)
    TextView tvForgotPassword;
    @BindView(R.id.iv_show_password_login)
    ImageButton ivShowPasswordLogin;
    private Call<LoginUserEntity> loginCall;

    @Override
    protected int layoutResID() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {

        rlClearPhone.setVisibility(etPhone.getText().toString().length() != 0 ? View.VISIBLE : View.INVISIBLE);
        rlClearPassword.setVisibility(etCode.getText().toString().length() != 0 ? View.VISIBLE : View.INVISIBLE);
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                etCode.setText("");
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    rlClearPhone.setVisibility(View.INVISIBLE);
                } else {
                    rlClearPhone.setVisibility(View.VISIBLE);
                }
            }
        });

        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                String content = charSequence.toString();
                if (charSequence.toString().length() == 0) {
                    rlClearPassword.setVisibility(View.INVISIBLE);
                    ivShowPasswordLogin.setVisibility(View.INVISIBLE);
                } else {
                    rlClearPassword.setVisibility(View.VISIBLE);
                    ivShowPasswordLogin.setVisibility(View.VISIBLE);
                }
                if (content.length() > 0) {
                    etCode.setSelection(content.length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        rlClearPhone.setOnClickListener(listener);
        rlClearPassword.setOnClickListener(listener);
        tvLogin.setOnClickListener(listener);
        tvRegist.setOnClickListener(listener);
        tvForgotPassword.setOnClickListener(listener);
        ivShowPasswordLogin.setOnClickListener(listener);


    }

    private boolean isShowPassword = false;

    private PerfectClickListener listener = new PerfectClickListener() {
        @Override
        protected void onNoDoubleClick(View view) {
            int id = view.getId();
            if (id == R.id.tv_login) {
                String phoneStr = etPhone.getText().toString();
                String code = etCode.getText().toString();
                if (TextUtils.isEmpty(phoneStr)) {
                    etPhone.requestFocus();
                    ToastUtils.showShortToastSafe("请输入手机号");
                    return;
                }
                if (TextUtils.isEmpty(code)) {
                    etCode.requestFocus();
                    ToastUtils.showShortToastSafe("请输入密码");
                    return;
                }
                //登录
                login();
            } else if (id == R.id.rl_clearPhone) {
                //清除手机号
                etPhone.getText().clear();
            } else if (id == R.id.rl_clearPassword) {
                //清除密码
                etCode.getText().clear();
            } else if (id == R.id.tv_regist) {
                //注册
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            } else if (id == R.id.tv_forgot_password) {
                //忘记密码
                startActivity(new Intent(LoginActivity.this, ForgotActivity.class));
            } else if (id == R.id.iv_show_password_login) {
                isShowPassword = !isShowPassword;
                isShowPassword();
            }

        }
    };

    private void isShowPassword() {
        if (isShowPassword) {
            // 显示密码
            etCode.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ivShowPasswordLogin.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_open));
        } else {
            // 隐藏密码
            etCode.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ivShowPasswordLogin.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_close));
        }
    }

    /**
     * 登录
     */
    private void login() {
        showProgress();

        String phone = etPhone.getText().toString().trim();
        String password = etCode.getText().toString().trim();
        loginCall = RetrofitHelper.getInstance().login(phone, password);
        loginCall.enqueue(new Callback<LoginUserEntity>() {
            @Override
            public void onResponse(Call<LoginUserEntity> call, Response<LoginUserEntity> response) {
                if (response != null) {
                    dismissProgress();
                    LoginUserEntity body = response.body();
                    if (body != null) {
                        String code = body.getCode();
                        if ("100".equals(code)) {
                            ToastUtils.showShortToastSafe(body.getRinfo());
                            LoginUserEntity.UserBean user = body.getUser();
                            if (user != null) {
                                int u_id = user.getU_id();          //用户id
                                String recode = user.getRecode();   //用户推荐码
                                String nick = user.getNick();       //用户昵称
                                String avatar = user.getAvatar();   //用户头像
                                //double money = user.getMoney();     //用户余额

                                SPUtils.getInstance().put(ConstantValue.SpType.userid, "" + u_id);
                                SPUtils.getInstance().put(ConstantValue.SpType.nick, nick);
                                //SPUtils.getInstance().put(ConstantValue.SpType.avatar, avatar);
                                SPUtils.getInstance().put(ConstantValue.SpType.newavatar, avatar);
                                SPUtils.getInstance().put(ConstantValue.SpType.recode, recode);
                                //SPUtils.getInstance().put(ConstantValue.SpType.money, "" + money);
                                SPUtils.getInstance().put(ConstantValue.SpType.account_username, phone);

                            }
                            SPUtils.getInstance().put(ConstantValue.SpType.cachekey, body.getCachekey());
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            intent.putExtra("new", true); //新手引导
                            startActivity(intent);
                            finish();

//                            Intent intent = new Intent(LoginActivity.this, MyInfoActivityUpdate.class);
//                            intent.putExtra("new", true); //新手引导
//                            startActivity(intent);
//                            finish();
                        } else {
                            ToastUtils.showShortToastSafe(body.getRinfo());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<LoginUserEntity> call, Throwable t) {
                Log.e("Login", t.getMessage());
                dismissProgress();
            }
        });


    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loginCall != null) {
            loginCall.cancel();
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
